<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入姓名" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 数据表格区域 -->
      <el-table
        :data="userList"
        stripe
        border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="switchToggle(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editBtn(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteBtn(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="权限管理" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="usersBtn(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="this.queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
        @close="resetDiolog"
        >
        <!-- 表单 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" type="password" clearable></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" type="email" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile" clearable></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibles">取 消</el-button>
    <el-button type="primary" @click="confirmDiolog">确 定</el-button>
  </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="resetEditDiolog"
      >
        <!-- 表单 -->
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" clearable disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" type="email" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile" clearable></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisibles">取 消</el-button>
    <el-button type="primary" @click="confirmEditDiolog">确 定</el-button>
  </span>
      </el-dialog>
      <!-- 分配角色对话框 -->

      <el-dialog
        title="分配角色"
        :visible.sync="RolesDialog"
        width="50%">
        <div>
          <p>当前用户：{{userInfo.username}}</p>
          <p>当前用户：{{userInfo.role_name}}</p>
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitUsers">确 定</el-button>
  </span>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 自定义验证方法
    var mobile = (rule, value, callback) => {
      const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    return {
      // 表格头部
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      // 添加用户表单
      addForm: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3~10位用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '请输入6~16位密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: mobile, trigger: 'blur' }
        ]
      },
      // 修改用户
      editDialogVisible: false,
      // 修改用户表单
      editId: '',
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 分配角色对话框
      RolesDialog: false,
      userInfo: {},
      userOptions: [],
      selectedRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 数据表格分页
    // 选择一页X条数据
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.queryInfo.pagesize = pageSize
      this.getUserList()
    },
    // 当前页面发生改变
    handleCurrentChange(currentPage) {
      this.queryInfo.pagenum = currentPage
      this.getUserList()
    },
    // 修改用户状态
    async switchToggle(user) {
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 添加用户按钮
    addUser() {
      this.dialogVisible = true
    },
    // 关闭对话框(清空表单)
    resetDiolog() {
      this.$refs.addFormRef.resetFields()
    },
    // 确定按钮，添加新用户
    confirmDiolog() {
      this.$refs.addFormRef.validate(async (res) => {
        if (!res) return this.$message.error('添加失败，请稍后重试!')
        // 发送请求
        const { data: resa } = await this.$http.post('users', this.addForm)
        if (resa.meta.status !== 201) return this.$message.error('添加失败，请稍后重试!')
        this.$message.success('添加用户成功!')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 修改按钮
    editBtn(scope) {
      console.log(scope)
      this.editForm.username = scope.username
      this.editForm.email = scope.email
      this.editForm.mobile = scope.mobile
      this.editId = scope.id
      this.editDialogVisible = !this.editDialogVisible
    },
    // 关闭对话框
    resetEditDiolog() {
      this.$refs.editFormRef.resetFields()
    },
    // 确定按钮，修改用户
    confirmEditDiolog() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请确认修改信息')
        const { data: res } = await this.$http.put(`users/${this.editId}`, this.editForm)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 对话框取消按钮
    dialogVisibles() {
      this.dialogVisible = false
    },
    // 修改对话框取消按钮
    editDialogVisibles() {
      this.editDialogVisible = false
    },
    // 删除用户按钮
    deleteBtn(scope) {
      this.$confirm('是否删除用户', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功',
          showClose: 'true'
        })
        this.$http.delete(`users/${scope.id}`)
        this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消退出',
          showClose: 'true'
        })
      })
    },
    // 分配角色对话框
    async usersBtn(scope) {
      this.RolesDialog = true
      this.userInfo = scope
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取信息失败，请刷新重试')
      this.$message.success('成功')
      console.log(res)
      this.userOptions = res.data
    },
    // 发送分配角色请求
    async submitUsers() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) return this.$message.error('获取信息失败，请刷新重试')
      this.$message.success('分配角色成功')
      this.RolesDialog = false
      this.getUserList()
    }
  }
}
</script>

<style scoped>

</style>
